﻿using HslCommunication;
using HslCommunication.Core;
using HslCommunication.Core.Pipe;
using HslCommunication.ModBus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NewDevice.RS485
{
    /// <summary>
    /// 中盛ZH4424系列电压/电流测试 值=读值*量程/10000
    /// </summary>
    public class ZH4424
    {
        private SerialBase_V2 _sb;
        private readonly ModbusRtu _modbusRtu;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="station"></param>
        /// <param name="pipe"></param>
        public ZH4424(byte station, SerialBase_V2 pipe)
        {
            _sb = pipe;
            _modbusRtu = new ModbusRtu();
            _modbusRtu.Station = station;
            _modbusRtu.DataFormat = DataFormat.ABCD;
            _modbusRtu.IsClearCacheBeforeRead = false;
            _modbusRtu.CommunicationPipe = pipe;
        }

        /// <summary>
        /// 通道数量
        /// </summary>
        public ushort ChannelCount { get; set; } = 24;

        /// <summary>
        /// 设备描述
        /// </summary>
        public string DeviceDescription { get; set; } = "ZH4424系列电压/电流采集卡";

        /// <summary>
        /// 量程
        /// </summary>
        public int Range { get; set; } = 30;

        /// <summary>
        /// 读取所有通道数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public List<double> ReadAllChannels()
        {
            List<double> results = new List<double>();
            try
            {
                OperateResult<short[]> readResult;
                lock (_sb.Locker)
                {
                    readResult = _modbusRtu.ReadInt16("24", ChannelCount);
                    Thread.Sleep(_sb.Delay);
                }

                if (!readResult.IsSuccess)
                {
                    throw new Exception($"读取数据失败: {readResult.Message}");
                }
                for (int i = 0; i < ChannelCount; i++)
                {
                    // 每个通道的数据由两个寄存器组成

                    int rawValue = readResult.Content[i];
                    // 计算实际值
                    double actualValue = rawValue * Range / 10000.0;
                    results.Add(actualValue);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"{DeviceDescription}读取所有通道数据时发生错误: {ex.Message}");
            }
            return results;
        }
    }
}